<?php

namespace app\common\model;

use think\db\exception\DbException;
use think\facade\Cache;
use think\Model;
use think\model\concern\SoftDelete;
use think\Paginator;

class BaseModel extends Model
{
    use SoftDelete;

    protected $deleteTime = 'delete_time';

    /**
     * 通用分页查询
     * @param array $where 查询条件
     * @param int $currentPage
     * @param int $pageSize 每页数量
     * @param string $order 排序规则
     * @return Paginator
     * @throws DbException
     */
    public function paginateList(array $where = [],int $currentPage = 1, int $pageSize = 15, string $order = 'id DESC'): Paginator
    {
        $cacheKey = $this->buildPageCacheKey($where, $currentPage, $pageSize, $order);
        $PageCacheTag = $this->getPageCacheTag();
        return $this->where($where)
                  ->cache($cacheKey, rand(240, 360),$PageCacheTag)
                  ->order($order)
                  ->paginate([
                        'list_rows' => $pageSize,
                        'page' => $currentPage
                ]);
    }

    /**
     * 生成分页的cachekey
     * @param array $where
     * @param int $currentPage
     * @param int $pageSize
     * @param string $order
     * @return string
     */
    protected function buildPageCacheKey(array $where = [],int $currentPage = 1, int $pageSize = 15, string $order = 'id DESC'): string{
        $currentPage = min($currentPage, 1000); // 限制最大1000页
        return sprintf(
            'page:%s:%s@page=%d&size=%d',  // 格式更清晰的key结构
            $this->getTable(),
            md5(json_encode([
                'where' => $where,
                'order' => $order
            ])),
            $currentPage,  // 加入页码
            $pageSize
        );
    }

    /**
     * 生成分页的tag
     * @return string
     */
    protected function getPageCacheTag(): string
    {
        return 'page_cache_' . $this->getTable();
    }

    /**
     * 修改数据时调用，删除标签时当前表下的所有分页查询的缓存
     * @return void
     */
    public function clearCacheByTag()
    {
        Cache::tag($this->getPageCacheTag())->clear();
    }
}